package org.rainbow.auctionplatform.service;

import org.rainbow.auctionplatform.bean.User;
import org.rainbow.auctionplatform.dao.RegisterMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RegisterService {

    // 插入成功
    public final static int INSERT_SUCCESS = 0;
    // 插入失败的其他错误
    public final static int INSERT_ERROR = -1;
    // 手机号重复
    public final static int INSERT_PHONE_DUPLICATE = -100;
    // 邮箱重复
    public final static int INSERT_EMAIL_DUPLICATE = -200;
    // QQ重复
    public final static int INSERT_QQ_DUPLICATE = -300;

    private final RegisterMapper registerMapper;

    @Autowired
    public RegisterService(RegisterMapper registerMapper) {
        this.registerMapper = registerMapper;
    }

    /**
     * 插入用户
     * @param user 需要出入的用户
     * @return 是否插入成功 0插入成功 -1手机号重复 -2邮箱重复
     */
    public int insertUser(User user) {
        // 插入成功标识
        boolean insert_flag;
        // 插入错误消息
        String error_msg = "";
        try {
            insert_flag = registerMapper.insertUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            // 获取错误消息
            error_msg = e.getCause().getMessage();
            insert_flag = false;
        }
        if (insert_flag) {
            return INSERT_SUCCESS;
        } else {
            // 重置MaxUid，防止出入失败后uid不连续
            resetMaxUid();
            if (!error_msg.isEmpty() && error_msg.contains("Duplicate")) {
                if (error_msg.contains("phone")) {
                    return INSERT_PHONE_DUPLICATE;
                } else if (error_msg.contains("email")) {
                    return INSERT_EMAIL_DUPLICATE;
                } else if (error_msg.contains("qq")) {
                    return INSERT_QQ_DUPLICATE;
                }
            }
            return INSERT_ERROR;
        }
    }

    /**
     * 重置自增id缓存
     * mysql的自增会在插入失败事务回滚时继续自增，所以需要在回滚后先查出实际的最大uid
     * 然后把缓存中的自增uid重置为最大uid+1
     */
    public void resetMaxUid() {
        int maxId;
        try {
            maxId = registerMapper.selectMaxUid();
        } catch (Exception e) {
            maxId = 10000;
        }
        if (maxId != 0) {
            registerMapper.resetMaxUid(maxId + 1);
        }
    }
}
